import 'package:flutter/material.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:get/get.dart';
import 'package:markdown_widget/markdown_widget.dart';

import '../../../../common/models/ai/index.dart';
import '../../../../common/models/id_data.dart';
import '../../../../common/models/meeting/meeting_info.dart';
import '../../../../common/models/orgs/o2_person.dart';
import '../../../../common/models/process/task_data.dart';
import '../../../../common/style/color.dart';
import '../../../../common/utils/log_util.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../../../../common/utils/o2_utils.dart';
import '../../../../common/widgets/o2_elevated_button.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import '../controller.dart';
import 'msg_body_static_bullet_list.dart';

class AIChatMsgBodyView extends GetView<AiController> {
  final AIChatInfo info;

  const AIChatMsgBodyView({Key? key, required this.info}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final result = AIMCPResultInfo.fromJson(
        O2Utils.parseStringToJson(info.content ?? '{}'));
    final name = result.name ?? '';
    switch (name) {
      case 'queryHr': // 查询人员信息
        final person = O2Person.fromJson(result.data);
        return _personInfoView(context, person);
      case 'createMeeting': // 创建会议
        final meeting = MeetingInfoForAIResponse.fromJson(result.data);
        final String extraMeetingId = info.extra?['meetingId'] ?? '';
        return _meetingInfoView(context, meeting, extraMeetingId);
      case 'queryTask': // 查询我的待办
        final list = result.data == null ? [] : result.data as List;
        final taskList = list.map((group) => TaskData.fromJson(group)).toList();
        return AIChatMsgBodyStaticBulletList(
            itemList: taskList
                .map((t) =>
                    '[${t.processName}] ${t.title ?? 'process_work_no_title_no_process'.tr}')
                .toList(),
            cardTitle: 'ai_task_my_list'.tr,
            onItemClick: (index) {
              final task = taskList[index];
              controller.clickViewTask(task);
            });
      case 'sendMail': // 发送邮件 (站内信)
        final id = IdData.fromJson(result.data);
        // 打开 站内信 门户
        final parameters = Uri.encodeComponent('{ "documentId": "${id.id}" }');
        final url = O2ApiManager.instance.getPortalUrl('mail',
                pageId: '0b0709c2-02ba-4576-b442-617377882bb6',
                portalParameters: parameters) ??
            "";
        return _markdownView('邮件发送成功, [点击查看邮件]($url)', linkOnTap: (url) {
          OLogger.d('点击了 url: $url');
          if (url.contains('portalmobile.html')) {
            controller.clickViewPortal('mail',
                pageId: '0b0709c2-02ba-4576-b442-617377882bb6',
                parameters: parameters);
          }
        });
      case 'createCalendar': // 创建日程
        final id = IdData.fromJson(result.data);
        final url = O2ApiManager.instance.getAppMobileUrl('Calendar');
        return _markdownView('已经为您创建好日程, [点击查看日程]($url)', linkOnTap: (url) {
          OLogger.d('点击了 url: $url');
          if (url.contains('appMobile.html?app=Calendar')) {
            controller.clickViewCalendarEventInfo(id.id ?? '');
          }
        });
      case 'startProcess_overtime': // 加班申请流程
        final res = AIProcessOvertimeResponse.fromJson(result.data);
        return _markdownView('已经为您提交好加班申请流程, [点击查看](work.html)', linkOnTap: (url) {
          OLogger.d('点击了 url: $url');
          if (url.contains('work.html')) {
            controller.clickViewWork(res.work ?? '', title: res.title);
          }
        });
      case 'statProcess': // 发文统计 echarts 图表
        return _echartsView(context, '''
          {
                title: {
                    text: '公文数量统计'
                },
                tooltip: {},
                legend: {
                    data: ['部门A', '部门B'],
                    top: '10%'
                },
                grid: {
                        left: '0%',
                        right: '0%',
                        bottom: '5%',
                        top: '15%',
                        height: '80%',
                        containLabel: true,
                        z: 22,
                      },
                xAxis: {
                    type: 'category',
                    data: ['发文', '收文', '会议纪要']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '部门A',
                        data: [120, 200, 150],
                        type: 'bar'
                    },
                    {
                        name: '部门B',
                        data: [110, 20, 250],
                        type: 'bar'
                    }
                ]
            }
        ''');
      default:
        final jsonStr = O2Utils.json2String(result.data, pretty: true);
        OLogger.e('未适配的消息 json $jsonStr');
        return _markdownView('[当前版本暂不支持查看此消息]\n```json\n$jsonStr\n```');
    }
  }


  Widget _echartsView(BuildContext context, String echartsOptions) {
    return SizedBox(
      height: 200,
      child:  Echarts(
      option: echartsOptions,
    ),
    );
  }

  Widget _meetingInfoView(BuildContext context,
      MeetingInfoForAIResponse meeting, String extraMeetingId) {
    final AICardViewInfo info = AICardViewInfo();
    info.title = 'meeting_info_title'.tr;
    final inviteList = meeting.inviteList?.join(',') ?? '';
    List<KeyValueViewInfo> attributeList = [];
    attributeList.add(KeyValueViewInfo(
        key: 'meeting_detail_title_label'.tr, value: meeting.subject ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'meeting_detail_room_label'.tr, value: meeting.room ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'meeting_detail_start_time_label'.tr,
        value: meeting.startTime ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'meeting_detail_completed_time_label'.tr,
        value: meeting.completedTime ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'meeting_detail_member_label'.tr, value: inviteList));
    info.attributeList = attributeList;
    // extraMeetingId 已经存在就是查看会议详情， 否则是确认提交会议
    if (extraMeetingId.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _cardView(context, info),
          _primaryButton(context, () => controller.clickSubmitMeeting(meeting),
              'ai_meeting_confirm_submit'.tr),
        ],
      );
    } else {
      info.moreBtnTitle = 'ai_meeting_view_detail'.tr;
      return _cardView(
        context,
        info,
        callback: () => controller.clickViewMeeting(extraMeetingId),
      );
    }
  }

  Widget _primaryButton(
      BuildContext context, VoidCallback onPressed, String text) {
    return Padding(
      padding: const EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 0),
      child: SizedBox(
          width: 120, // double.infinity,
          height: 44,
          child: O2ElevatedButton(
              onPressed,
              Text(
                text,
                style: const TextStyle(fontSize: 16),
              ),
              radius: 4)),
    );
  }

  Widget _personInfoView(BuildContext context, O2Person p) {
    final AICardViewInfo info = AICardViewInfo();
    info.title = p.name ?? '';
    List<KeyValueViewInfo> attributeList = [];
    attributeList
        .add(KeyValueViewInfo(key: 'my_profile_name'.tr, value: p.name ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'my_profile_employee'.tr, value: p.employee ?? ''));
    attributeList.add(
        KeyValueViewInfo(key: 'my_profile_mobile'.tr, value: p.mobile ?? ''));
    attributeList
        .add(KeyValueViewInfo(key: 'my_profile_email'.tr, value: p.mail ?? ''));
    attributeList.add(KeyValueViewInfo(
        key: 'my_profile_office_phone'.tr, value: p.officePhone ?? ''));
    info.attributeList = attributeList;
    return _cardView(context, info,
        callback: () => controller.clickEnterPerson(p));
  }

  Widget _cardView(BuildContext context, AICardViewInfo info,
      {GestureTapCallback? callback}) {
    List<Widget> list = [];
    if (info.attributeList != null && info.attributeList!.isNotEmpty) {
      list = info.attributeList!
          .map((a) => O2UI.lineWidget(a.key,
              Text(a.value, style: Theme.of(context).textTheme.bodySmall)))
          .toList();
    }
    final card = Card(
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            child: Column(
              children: [
                Padding(
                    padding: const EdgeInsets.only(bottom: 10, left: 5),
                    child: Row(children: [
                      Text(info.title ?? '',
                          style: Theme.of(context)
                              .textTheme
                              .bodyLarge
                              ?.copyWith(fontWeight: FontWeight.w500)),
                      const Spacer()
                    ])),
                const Divider(height: 1),
                ...list,
                if (callback != null) const Divider(height: 1),
                if (callback != null)
                  Padding(
                      padding: const EdgeInsets.only(top: 10, left: 5),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                              info.moreBtnTitle ??
                                  'im_instant_msg_detail_btn_title'.tr,
                              style: Theme.of(context).textTheme.bodySmall),
                          const Spacer(),
                          const Icon(
                            Icons.arrow_forward_ios,
                            size: 22,
                            color: AppColor.hintText,
                          ),
                          const SizedBox(width: 5),
                        ],
                      ))
              ],
            )));
    if (callback != null) {
      return GestureDetector(
        onTap: () => callback(),
        child: card,
      );
    } else {
      return card;
    }
  }

  void defaultLinkTap(String url) {
    OLogger.d('点击了链接 $url');
  }

  Widget _markdownView(String mdContent, {ValueCallback<String>? linkOnTap}) {
    linkOnTap ??= defaultLinkTap;
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: MarkdownGenerator().buildWidgets(mdContent,
            config: MarkdownConfig(configs: [
              const PConfig(textStyle: TextStyle(fontSize: 14)),
              const H1Config(
                  style: TextStyle(
                fontSize: 24,
                height: 40 / 32,
                fontWeight: FontWeight.bold,
              )),
              const H2Config(
                  style: TextStyle(
                fontSize: 20,
                height: 30 / 24,
                fontWeight: FontWeight.bold,
              )),
              const H3Config(
                  style: TextStyle(
                fontSize: 18,
                height: 25 / 20,
                fontWeight: FontWeight.bold,
              )),
              LinkConfig(
                style: const TextStyle(
                  fontSize: 16,
                  color: Color(0xff0969da), 
                  decoration: TextDecoration.underline),
                onTap: linkOnTap,
              ),
            ])));
  }
}
